from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *
import jwt
from django_md.settings import SECRET_KEY

from rest_framework.authentication import BaseAuthentication


# 自定义我们自己的 令牌认证类
class MyTokenAuth(BaseAuthentication):
    def authenticate(self, request):
        # 解析令牌
        token = request.GET.get("token")
        uid = jwt.decode(token, SECRET_KEY)["uid"]
        user = UserProfile.objects.get(id=uid)
        # 返回 是一个元组 第一个是 用户对象 第二个是 令牌

        return (user, token)


# 根据用户id 查找用户的详细信息

class UserDetailView(APIView):
    authentication_classes = [MyTokenAuth]

    def get(self, request):
        user = request.user

        print("user:", user)
        user = UserProfile.objects.get(id=user.id)

        ser = UserDetailSer(user)
        return Response(ser.data)

    def put(self, request):
        user = request.user
        # 1、更新 用户的信息，:邮箱、密码
        email = request.data.get("email")
        user.email = email
        # 修改
        user.save()

        return Response({"msg": "绑定邮箱"})


class UserPasswordView(APIView):
    authentication_classes = [MyTokenAuth]

    def post(self, request):
        user = request.user
        print(user)
        password = request.data.get("password")
        new_password = request.data.get("password1")

        if user.check_password(password):
            # 修改密码
            #  Django 的 User 设置密码 使用set_password  内部会加密密码的
            user.set_password(new_password)
            return Response({"msg": "密码修改成功", "code": 200})
        else:

            return Response({"msg": "当前密码不正确", "code": 400})


# 定义 省市县的 接口

class CityView(APIView):

    def get(self, request):
        pid = request.GET.get("pid")
        queryset = City.objects.filter(parentid=pid)

        ser = CitySer(queryset, many=True)

        return Response(ser.data)


# 地址接口 实现 查询、添加

class AddressView(APIView):
    authentication_classes = [MyTokenAuth]

    def post(self, request):
        request.data["user"] = request.user.id
        ser = AddressSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg": "添加成功", "code": 200})
        else:
            print(ser.errors)
            return Response({"msg": "添加失败", "code": 400})

    def get(self, request):
        # 获取 用户的所有地址
        queryset = Address.objects.filter(user_id=request.user.id)
        ser = AddressListSer(queryset, many=True)
        return Response(ser.data)